<template>
  <el-drawer
    v-model="props.visible"
    title="发起审批"
    direction="rtl"
    size="40%"
  >
    <el-row>
      <el-col
        :span="8"
        v-for="workflow in allWorkflows"
        :key="workflow.id"
        @click="createTask(workflow)"
      >
        <el-card :shadow="selectedWorkflowId === workflow.id ? 'always' : 'hover'">{{ workflow.name }}</el-card>
      </el-col>
    </el-row>
    <CreateTaskDrawer
      v-model="createDialog.visible"
      :workflow-id="createDialog.workflowId"
      :workflow-name="createDialog.workflowName"
      :workflow-version="createDialog.workflowVersion"
      @closed="onClose"
    />
  </el-drawer>
</template>

<script setup>
import { defineProps, watch, ref, nextTick, onMounted } from "vue";
import { useWorkflowDesignStore } from "@/stores/workflowDesign";
import CreateTaskDrawer from "./CreateTaskDrawer.vue";

const props = defineProps({
  visible: {
    default: true,
  },
});
const emit = defineEmits(["update:visible", "closed"]);
const loading = ref(false);
const allWorkflows = ref([]);
const createDialog = ref({
  visible: false,
  workflowId: "",
  workflowName: "",
  workflowVersion: 0,
});

const selectedWorkflowId = ref("");
watch(
  () => props.visible,
  () => {
    if (!props.visible) {
      getAllWorkflowsWithVersion();
    }
  }
);

const workflowDesignStore = useWorkflowDesignStore();
const getAllWorkflowsWithVersion = () => {
  loading.value = true;
  workflowDesignStore.getAllWorkflowsWithDefaultVersion({}).then((res) => {
    allWorkflows.value = res;
    loading.value = false;
  });
};

const createTask = (workflowItem) => {
  createDialog.value.workflowId = workflowItem.id;
  createDialog.value.workflowName = workflowItem.name;
  createDialog.value.visible = true;
  createDialog.value.workflowVersion = workflowItem.activeVersion;
  selectedWorkflowId.value = workflowItem.id;
};
const onClose = () => {
  createDialog.value.workflowId = "";
  createDialog.value.visible = false;
  emit("closed");
  emit("update:visible", false);
};
onMounted(() => {
  getAllWorkflowsWithVersion();
});
</script>

<style lang="less" scoped>
.el-col {
  padding: 5px;
}
.el-col .el-card {
  cursor: pointer;
}
:deep(.is-always-shadow) {
  background: #409EFF;
  color: #ffffff;
}
</style>
